#
# The Linux Counter object.
#
# Knows altogether too much about counter internal structures....
#
package Counter;

use POSIX qw(strftime);

use FileTable;
use Fcntl;
use strict;
use vars qw(@ISA);
use Carp;

# The following jumk just to get by the RDWR check...
use Validate::Machines;
#use Validate::Usergroups;
#use Validate::Friends;
use Validate::Persons;

require Counter::User;

@ISA = qw(FileTable);

use vars qw($dbprefix %files %vars $website);


sub init {

    my $root;
    if ($ENV{COUNTER_ROOT}) {
	$root = $ENV{COUNTER_ROOT};
    } else {
	$root = "/counter/root/not/set";
    }
    $dbprefix = "$root/db";
# open-file table
    %files = ();
    # initfile
    my $initfile = $root . "/.counter.ini";
    # Read init file. Not thought through yet!
    if (open(INI, $initfile)) {
	while (<INI>) {
	    chop;
	    if (/^(\S+)=/) {
		my $varname = $1;
		if ($varname eq "homedir") {
		    if ($' ne $root) { # ';
			die "INI file and given root are inconsistent\n";
		    }
		}
		$vars{$varname} = $'; # ';
	    }
	}
    } else {
	#warn "No init file\n";
    }

    if ($vars{website}) {
    $website = "i18n." . $vars{website};
    }

    # Manipulate our FileTable based on variables
    if ($vars{dbname}) {
	$FileTable::database = $vars{dbname};
    }
    if ($vars{dbhost}) {
	$FileTable::databaseserver = $vars{dbhost};
    }
    #warn "Finished Counter.pm init - dbprefix $dbprefix\n";
}

init();

sub website {
    if ($website) {
        return $website;
    } else {
        carp "Counter.pm: website variable not intitialized - fix!";
        return "i18n.counter.li.org";
    }
}
						    
sub open {
    my $res = openfile("users", @_);
    bless $res;
    $res;
}

# Internal file-opening method
sub openfile {
    my $name = shift;
    if (!$files{$name}) {
	$files{$name} = FileTable::open("$dbprefix/$name", O_RDWR);
    } else {
    }
    return $files{$name};
}

sub getbyemail {
    my $self = shift;
    my $mail = shift;
    my $email;
    my $emails;

    $emails = openfile("email");
    $email = $emails->get($mail);
    if ($email) {
	return $self->get($email->{owner});
    } else {
	return undef;
    }
}

sub timestring {

    my $time = shift;

    my $tstring = strftime("%Y-%m-%d %H:%M:%S", gmtime($time));
}

sub root {
    return $vars{homedir};
}
   

1;


